<template>
	<NavBar :obj="{ title: '开店申请', color: '#000', backgroundColor: '#fff' }" />

	<view style="padding-bottom: 220rpx">
		<view class="layout-box">
			<view class="layout" @click="goShareholder">
				<view class="label">添加股东</view>
				<view class="inp">{{ shareholder.length > 0 ? shareholder.length + '个' : '未添加' }}</view>
				<u-icon name="arrow-right" color="#333" size="16" class="arrow-down"></u-icon>
			</view>
		</view>

		<view class="layout-box">
			<view class="layout">
				<view class="label">门店类型</view>
				<view class="inp" @click="typeShow = true">{{ chosTitle }}</view>
				<u-icon name="arrow-right" color="#333" size="16" class="arrow-down"></u-icon>
			</view>
		</view>

		<view class="layout-box">
			<view class="layout">
				<view class="label">门店名称</view>
				<input class="inp" placeholder-class="place-inp" placeholder="请填写门店名称" v-model="formRef.title" />
			</view>
			<view class="layout">
				<view class="label">店主姓名</view>
				<input class="inp" placeholder-class="place-inp" placeholder="请填写店主姓名" v-model="formRef.shopkeeper" />
			</view>

			<view class="layout">
				<view class="label">手机号</view>
				<input class="inp" type="number" placeholder-class="place-inp" placeholder="请填写手机号" v-model="formRef.mobile" />
			</view>

			<view class="layout">
				<view class="label">所在省市</view>
				<view class="tips" :class="{ inp: formRef.address, 'place-inp': !formRef.address }" @click="pickArea">
					{{ formRef.address ? formRef.address : '点击选择所在省市区' }}
				</view>
				<up-icon name="arrow-down" size="15" class="icon" color="#bdbdbd"></up-icon>
			</view>
			<view class="layout">
				<view class="label">详细地址</view>
				<textarea class="inp textarea" placeholder-class="place-inp" placeholder="请填写详细地址" v-model="formRef.address_details"></textarea>
			</view>
		</view>

		<view class="layout-box">
			<view class="layout" style="justify-content: start">
				<view class="label">营业执照</view>
				<Upload v-model="files" :maxCount="1" @change="handleChange" />
			</view>

			<view class="layout" style="justify-content: start">
				<view class="label">门头照片</view>
				<Upload v-model="filesMt" :maxCount="1" @change="handleChangeMt" />
			</view>
		</view>

		<view class="layout-box" v-if="reject_msg">
			<view class="layout">
				<view class="label">驳回原因</view>
				<view class="inp" style="color: red">{{ reject_msg }}</view>
			</view>
		</view>
	</view>

	<view class="fixed-bottom" v-if="!status || status == 3" @click="apply">
		<view class="btn" :class="{ gray: status && status == 1 }">
			<text>提交申请</text>
		</view>
	</view>

	<view class="fixed-bottom" v-if="status == 1">
		<view class="btn" :class="{ gray: status && status == 1 }">
			<text>审核中</text>
		</view>
	</view>

	<view class="fixed-bottom" v-if="status == 2">
		<view class="btn" :class="{ gray: status && status == 1 }">
			<text>您已是门店</text>
		</view>
	</view>

	<up-overlay :show="overlay" opacity="0" zIndex="100"></up-overlay>
	<up-picker
		confirmColor="#F81A2E"
		:show="areaShow"
		ref="uPickerRef"
		:defaultIndex="defaultIndex"
		keyName="title"
		:loading="pickerLoading"
		:columns="columns"
		:closeOnClickOverlay="true"
		@close="areaShow = false"
		@confirm="confirm"
		@cancel="areaShow = false"
		@change="changeHandler"
	></up-picker>

	<u-picker
		:defaultIndex="defaultCateIndex"
		:show="typeShow"
		:columns="[typeList]"
		@cancel="typeShow = false"
		@confirm="confirmType"
		keyName="title"
		confirmColor="#FB3204"
	></u-picker>
</template>

<script setup>
	import { ref, nextTick, reactive } from 'vue';
	import { port, imgUrl, goUrl, hint, loading, closeLoading, goBack, goIndex } from '../../service/port';
	import { onLoad, onShow, onUnload, onReachBottom } from '@dcloudio/uni-app';
	import Upload from '/components/Uploads.vue';
	const areaRef = ref({
		level: 0,
		pid: 0
	});
	const choose = ref('');
	const defaultIndex = ref([0, 0, 0]);
	const areaShow = ref(false);
	const uPickerRef = ref(null);
	const pickerLoading = ref(false);
	const columns = ref([['请选择省'], ['请选择市'], ['请选择区/县']]);
	const init = ref(false);
	const status = ref(0);
	const reject_msg = ref('');
	const formRef = ref({
		cate_id: '',
		shareholder_ids: '',
		title: '',
		shopkeeper: '',
		mobile: '',
		province: '',
		city: '',
		district: '',
		address_details: '',
		default: 0,
		address: '',
		license: '',
		cover: ''
	});
	const overlay = ref(false);
	const files = ref([]);
	const handleChange = (event) => {
		const images = files.value.map((i) => {
			return i.url;
		});
		formRef.value.license = images.length > 0 ? images.join(',') : '';
	};

	const filesMt = ref([]);
	const handleChangeMt = (event) => {
		const images = filesMt.value.map((i) => {
			return i.url;
		});
		formRef.value.cover = images.length > 0 ? images.join(',') : '';
	};

	const typeShow = ref(false);
	const typeList = ref({});
	const chosTitle = ref('请选择');
	const defaultCateIndex = ref([0]);
	const shareholder = ref([]);
	function confirmType(e) {
		formRef.value.cate_id = e.value[0].id;
		chosTitle.value = e.value[0].title;
		typeShow.value = false;
	}

	const changeHandler = async (e) => {
		pickerLoading.value = true;
		const { columnIndex, value, values, index, indexs } = e;

		if (columnIndex < 2) {
			await getArea(columnIndex + 1, columns.value[columnIndex][index].id);
			if (!columnIndex) {
				await nextTick();
				await getArea(columnIndex + 2, columns.value[columnIndex + 1][0].id);
				pickerLoading.value = false;
			}

			if (!columnIndex) {
				defaultIndex.value = [index, 0, 0];
			} else {
				indexs[2] = 0;
				defaultIndex.value = indexs;
			}
			nextTick(() => {
				uPickerRef.value?.setIndexs(defaultIndex.value);
			});
			pickerLoading.value = false;
		} else {
			defaultIndex.value[2] = index;
			pickerLoading.value = false;
		}
	};

	const confirm = (e) => {
		let a = '',
			k = ['province', 'city', 'district'];
		defaultIndex.value.map((v, i) => {
			a += columns.value[i][v].title;
			formRef.value[k[i]] = columns.value[i][v].id;
		});
		formRef.value.address = a;
		areaShow.value = false;
	};

	onUnload(() => {
		uni.removeStorageSync('shareholder');
	});
	const isLoad = ref(false);
	onShow(() => {
		if (!isLoad.value) {
			getShopCate();
			getShopInfo();

			setTimeout(() => {
				shareholder.value = uni.getStorageSync('shareholder');
				if (shareholder.value) {
					let ids = [];
					shareholder.value.map((v) => {
						ids.push(v.id);
					});

					formRef.value.shareholder_ids = ids.length > 0 ? ids.join(',') : '';
				}
			}, 300);
		} else {
			isLoad.value = true;
		}
	});

	function goShareholder() {
		isLoad.value = false;
		goUrl('/pages/shop/shareholder');
	}

	async function apply() {
		if (!formRef.value.shareholder_ids) {
			hint('请添加股东');
			return false;
		}
		if (!formRef.value.cate_id) {
			hint('请选择门店类型');
			return false;
		}
		if (!formRef.value.title) {
			hint('请填写门店名称');
			return false;
		}
		if (!formRef.value.shopkeeper) {
			hint('请填写店主名称');
			return false;
		}
		if (!formRef.value.mobile) {
			hint('请填写手机号');
			return false;
		}
		if (!formRef.value.province || !formRef.value.city || !formRef.value.district) {
			hint('请选择所在省市');
			return false;
		}
		if (!formRef.value.address_details) {
			hint('请填写详细地址');
			return false;
		}
		if (!formRef.value.license) {
			hint('请上传营业执照');
			return false;
		}
		if (!formRef.value.cover) {
			hint('请上传门店封面');
			return false;
		}

		loading();
		let res = await port('applyShop', formRef.value);
		setTimeout(() => {
			closeLoading();
			uni.removeStorageSync('shareholder');
			getShopInfo();
		}, 300);
	}

	function getShopInfo() {
		uni.request({
			url: imgUrl + 'api/shop/info',
			method: 'GET',
			header: {
				token: uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
			},
			success: (e) => {
				let res = e.data;
				if (res.data) {
					overlay.value = true;
					chosTitle.value = res.data.cate.title;

					typeList.value.map((v, i) => {
						if (v.id == res.data.cate.id) {
							defaultCateIndex.value = [i];
						}
					});

					files.value = [{ url: imgUrl + res.data.license }];
					filesMt.value = [{ url: imgUrl + res.data.cover }];

					let ids = [];
					let users = [];
					res.data.shareholder.map((v) => {
						ids.push(v.uid);
						users.push(v.user);
					});

					formRef.value = {
						cate_id: res.data.cate.id,
						shareholder_ids: ids.length > 0 ? ids.join(',') : '',
						title: res.data.title,
						shopkeeper: res.data.shopkeeper,
						mobile: res.data.mobile,
						province: res.data.province,
						city: res.data.city,
						district: res.data.district,
						address_details: res.data.address_details,
						default: 0,
						address: res.data.province_title + res.data.city_title + res.data.district_title,
						license: res.data.license,
						cover: res.data.cover
					};

					status.value = res.data.audit_status;
					reject_msg.value = res.data.reject_msg;

					formRef.value.shareholder_ids = ids.length > 0 ? ids.join(',') : '';

					if (users.length > 0) {
						uni.setStorageSync('shareholder', users);
					}

					getNextArea();
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	}

	async function getShopCate() {
		let res = await port('getShopCate');
		typeList.value = res.data;
	}

	async function getAddressInfo() {
		let res = await port('getAddressInfo', { id: formRef.value.id });
		formRef.value = {
			...res.data
		};
		await getNextArea();
	}

	async function pickArea() {
		if (!init.value) {
			loading();
			await getNextArea();
		}
		areaShow.value = true;
	}

	async function getNextArea() {
		loading();
		await getArea();
		await nextTick();
		if (formRef.value.id) {
			await getArea(1, formRef.value.province);
			await nextTick();
			await getArea(2, formRef.value.city);

			let k = ['province', 'city', 'district'];
			defaultIndex.value.forEach((v, i) => {
				columns.value[i].forEach((vv, ii) => {
					if (vv.id == parseInt(formRef.value[k[i]])) {
						defaultIndex.value[i] = ii;
					}
				});
			});

			nextTick(() => {
				uPickerRef.value?.setIndexs(defaultIndex.value);
			});
		} else {
			await getArea(1, columns.value[0][defaultIndex.value[0]].id);
			await nextTick();
			await getArea(2, columns.value[1][defaultIndex.value[1]].id);
		}

		closeLoading();
		init.value = true;
	}

	async function getArea(level = 0, pid = 0) {
		let res = await port('getArea', { level: level, pid: pid });
		columns.value[level] = res.data;
	}
</script>

<style scoped lang="scss">
	:global(page) {
		background-color: #f0f0f0;
	}
	.gray {
		background: gray;
	}

	.tips {
		font-size: 28rpx;
		color: #bdbdbd;
	}

	.layout-box {
		background: #ffffff;
		border-radius: 20rpx;
		margin: 26rpx 30rpx;
		padding: 0 23rpx;
		.layout {
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eeeeee;
			display: flex;

			justify-content: space-between;
			&:last-child {
				border-bottom: none;
			}
			.label {
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				width: 27%;
			}
			.inp {
				font-size: 28rpx;
				color: #333333;
				flex: 1 1 0%;
			}
			.place-inp {
				color: #bdbdbd;
				flex: 1 1 0%;
			}
			.textarea {
				height: 120rpx;
			}
			.icon {
				margin-right: 30rpx;
			}
		}
	}
</style>
